﻿//-----------------------------------------------------------------------
// <copyright file="SessionRepository.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Infrastructure.AspNetProviders.Repositories
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.IO.Compression;
    using System.Text;
    using System.Web;
    using System.Web.Security;
    using AbstractSaaSTemplate.Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Repositories;
    using AbstractSaaSTemplate.Infrastructure.AspNetProviders.Exceptions;

    /// <summary>
    /// Implements 'ISessionsRepository' and all its contract, providing
    /// data accessibility to the aggregate 'Sessions'.
    /// </summary>
    public class SessionRepository : ISessionRepository
    {
        /// <summary>
        /// Defines the key to access the session within the
        /// HttpContext.Session instance of HttpSessionState.
        /// </summary>
        private const string SessionDataKey = "SessionData";

        /// <summary>
        /// Gets the active session if any.
        /// If no session is active, returns null.
        /// </summary>
        public Session ActiveSession
        {
            get
            {
                return CreateOrRetrieveSessionDataFromHttpSessionState();
            }
        }

        /// <summary>
        /// Creates or updates a 'Session' in the system.
        /// </summary>
        /// <param name="entity">The entry of 'Session' which will be either created or updated.</param>
        public void AddOrUpdateSession(Session entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            // sets the current data of session to the HttpContext session
            var sessionData = CreateOrRetrieveSessionDataFromHttpSessionState(entity);

            // logs the user using the FormsAuthentication
            if (!string.IsNullOrWhiteSpace(sessionData.OwnerLogin))
            {
                EnsureHttpContext();

                if (HttpContext.Current.User != null)
                {
                    var identity = HttpContext.Current.User.Identity;
                    if (identity != null && !identity.IsAuthenticated)
                    {
                        FormsAuthentication.SetAuthCookie(
                            entity.OwnerLogin,
                            entity.IsPersistent);
                    }
                }
            }
        }

        /// <summary>
        /// Deletes a particular 'Session'
        /// </summary>
        /// <param name="entity">The entity which should be deleted.</param>
        public void DeleteSession(Session entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            FormsAuthentication.SignOut();

            if (HttpContext.Current == null)
            {
                return;
            }

            if (HttpContext.Current.Session == null)
            {
                return;
            }

            HttpContext.Current.Session.Clear();
            HttpContext.Current.Session.Abandon();
        }

        /// <summary>
        /// Makes sure that the HttpContext and HttpSessionState
        /// within the contexta are valid.
        /// </summary>
        private static void EnsureHttpContext()
        {
            if (HttpContext.Current == null)
            {
                throw new InvalidHttpContextException();
            }
        }

        /// <summary>
        /// Attemps to retrieve an instance of session from the
        /// HttpContext.Session. If there's no instance avaliable,
        /// create a new one to it.
        /// </summary>
        /// <returns>Returns an instance of Session with the current HttpSessionState info</returns>
        private static Session CreateOrRetrieveSessionDataFromHttpSessionState()
        {
            return CreateOrRetrieveSessionDataFromHttpSessionState(null);
        }

        /// <summary>
        /// Attemps to retrieve an instance of session from the
        /// HttpContext.Session. If there's no instance avaliable,
        /// create a new one to it.
        /// </summary>
        /// <param name="data">The data which can be used to create a session</param>
        /// <returns>Returns an instance of Session with the current HttpSessionState info</returns>
        private static Session CreateOrRetrieveSessionDataFromHttpSessionState(Session data)
        {
            EnsureHttpContext();

            // we retrieve the currentData from the session state
            // if tehre is any session state available
            var session = HttpContext.Current.Session;
            var requestCookies = HttpContext.Current.Request.Cookies;
            var responseCookies = HttpContext.Current.Response.Cookies;
            var currentData = null as Session;
            if (session != null)
            {
                currentData = session[SessionDataKey] as Session;
            }

            // if we could not find the sessionData in the active session,
            // we will attempt to find it in the cookie. Cookies live
            // longer than the session. Ignoring its availability can
            // cause SERIOUS problems for procedures that consider the user
            // state to operate so, please, make sure this or any alternative
            // is in place to prevent that in environments that cookies are
            // not allowed.
            if (currentData == null)
            {
                var sessionDataCookie = requestCookies[SessionDataKey];
                if (sessionDataCookie != null && !string.IsNullOrWhiteSpace(sessionDataCookie.Value))
                {
                    var xmlData = Inflate(sessionDataCookie.Value);
                    currentData = Session.FromXml(xmlData);
                }
            }

            // if no session data (null) is defined
            // we create a session with the very default data it deserves
            if (data == null && currentData != null)
            {
                data = currentData;
            }
            else if (data == null)
            {
                data = new Session()
                {
                    Culture = CultureInfo.CurrentUICulture,
                    IsPersistent = false
                };

                // if the session is set to a user, it means that we
                // have a user logged on and we should behave like so.
                if (HttpContext.Current.User != null)
                {
                    data.OwnerLogin = HttpContext.Current.User.Identity.Name;
                }
            }

            // in case there is no session state, we simply return
            // the session data without any link to the session
            // this should happen only for session-less requests
            // such as the ones related to images, etc.
            // the problem related to it showed up when running the
            // application in the dev webserver, because it was trowing
            // an exception related to a null HttpContext.Session
            // when requesting the site assets.
            if (session == null)
            {
                return data;
            }

            // we check the session Id
            var areIdEquals = string.Compare(
                session.SessionID,
                data.Id,
                StringComparison.Ordinal) == 0;

            if (!areIdEquals)
            {
                data.Id = session.SessionID;
            }

            // we now try to retrieve the currentData
            // if there is any, we will update the
            // current instead of creating a new one
            if (currentData == null)
            {
                session[SessionDataKey] = data;
                responseCookies[SessionDataKey].Value = Deflate(data.ToXml());
                currentData = data;
            }
            else
            {
                currentData.OwnerLogin = data.OwnerLogin;
                currentData.IsPersistent = data.IsPersistent;
                currentData.Culture = data.Culture;

                if (data.Culture == null)
                {
                    data.Culture = CultureInfo.CurrentUICulture;
                }
            }

            // if from cookies does not work, we shall get the
            // current ui culture, that should match the user's browser.
            if (data.Culture == null)
            {
                data.Culture = CultureInfo.CurrentUICulture;
            }

            // we update the session's Culture
            // regardless what we had so already
            session.LCID = data.Culture.LCID;
            return data;
        }

        /// <summary>
        /// Compresses data for cookies using the Deflate algorithm.
        /// </summary>
        /// <param name="data">The data that will be compressed.</param>
        /// <returns>Returns the data compressed.</returns>
        private static string Deflate(string data)
        {
            var originalBuffer = Encoding.Unicode.GetBytes(data);
            var compressedData = null as byte[];

            // we create the memory stream to which the output data
            using (var output = new MemoryStream())
            {
                // now we create the compression stream that will
                // be used to compress the data into a byte[].
                using (var deflate = new DeflateStream(output, CompressionMode.Compress))
                {
                    // finally, we use the stream writer to write it, UTF8
                    using (var writer = new StreamWriter(deflate, Encoding.UTF8))
                    {
                        writer.Write(data);
                    }
                }

                compressedData = output.ToArray();
            }

            return Convert.ToBase64String(compressedData);
        }

        /// <summary>
        /// Uncompress data for cookies using the Deflate algorith.
        /// </summary>
        /// <param name="compressed">The base 64 string with compressed data</param>
        /// <returns>Returns uncompressed data.</returns>
        private static string Inflate(string compressed)
        {
            var compressedData = Convert.FromBase64String(compressed);
            var originalBuffer = null as byte[];

            // we create the memory stream that will be used to keep
            // and make readable any compressed data passed on to here.
            using (var stream = new MemoryStream(compressedData))
            {
                // we create the deflate stream to decompress the data
                using (var deflate = new DeflateStream(stream, CompressionMode.Decompress))
                {
                    // finally we use a stream reader using unicode encoding
                    // that allows us to read the outcome of the inflated data.
                    using (var reader = new StreamReader(deflate, Encoding.UTF8))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
        }
    }
}